package com.dfrz.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.easysdk.factory.Factory;
import com.dfrz.config.AlipayTemplate;

import com.dfrz.entity.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 支付宝接口
 */
@Controller
@RequestMapping("/alipay")
public class AliPayController {

    @Resource
    AlipayTemplate alipayTemplate;

    @Resource
    UserController userController;
    @GetMapping("/pay")
    @ResponseBody
    //用户账号：xlvwkd1131@sandbox.com
    //用户密码：111111
    //natapp -authtoken=70559fe44489e518
    public String pay(Integer uid) throws AlipayApiException {
        Order order = new Order();
        Random random=new Random();
        String id="";
        id+=uid;
        for (int i = 0; i <14 ; i++) {
            id+=random.nextInt(10);
        }
        order.setId(Long.parseLong(id));
        order.setUserId(129904058947L);
        order.setName("mikufun会员");
        order.setMoney(30.0);
        order.setPaymentMethod("支付宝");
        String content=alipayTemplate.pay(order);
        return content;
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            char[] arr= params.get("out_trade_no").toCharArray();
            int i=arr.length-14;
            String id="";
            for (int j = 0; j <i ; j++) {
                id+=arr[j];
            }
            userController.vip(Integer.parseInt(id));
        }
        return "success";
    }
}

